<!--- Only users who have logged in can access the controller
<cfif NOT IsUserLoggedIn()>
	<cflocation url="/csac" addtoken="no" />
	<cfabort>
</cfif> --->

<!--- set action to debug to dump incoming variables --->
<cfparam name="action" type="string" default="">

<cfif action eq "debug">
	<h1>ARGS</h1>
	<p>ARGS collection will set to the first of FORM, URL or REQUEST scopes that has an ACTION parameter.</p>
	<p>For this submission, ARGS set from...</p>
	<cfif StructKeyExists(form, "action")>
		<h2>FORM</h2>
		<cfdump var="#form#" label="ARGS" expand="no">
	<cfelseif StructKeyExists(url, "action")>
		<h2>URL</h2>
		<cfdump var="#url#" label="ARGS" expand="no">
	<cfelseif StructKeyExists(request, "action")>
		<h2>REQUEST</h2>
		<cfdump var="#request#" label="ARGS" expand="no">
	<cfelse>
		<h2>ACTION not found</h2>
		<p>ACTION parameter not found in scopes.  ARGS set to empty struct.</p>
		<cfdump var="#StructNew()#" label="New empty struct" expand="yes">
	</cfif>
	<cfabort>
</cfif>

<cfscript>
	if (IsDefined("form.action")) {
		// deep copy - no references
		args = Duplicate(form);
	} else if (IsDefined("url.action")) {
		// deep copy - no references
		args = Duplicate(url);
	} else if (IsDefined("request.action")) {
		// shallow copy - with references
		args = StructCopy(request);
	} else {
		args = StructNew();
	};
	if (StructCount(args) gt 0) {

		switch(args.action) {
			case "filter":
				args.filter = form;
				request.Base.setUIFilter(argumentCollection = args);
			break;
			case "resetFilter":
				if (IsWDDX(form.defaultFilter)) {
					args.filter = request.Base.wddxToCFML(form.defaultFilter);
				} else {
					args.filter = form.defaultFilter;	
				}
				request.Base.setUIFilter(argumentCollection = args);
			break;
			case "import":
				/*if (StructKeyExists(args, "fileField") and StructKeyExists(args, args.fileField) and StructKeyExists(args, "collection")) {
					upload = request.base.uploadFormFile(argumentCollection = args);
					if (upload.fileWasSaved) {
						uploadFile = upload.ServerDirectory & "\" & upload.ServerFile;
						switch(args.collection) {
							case "followUps":
								if (upload.serverFileExt neq "xls" and upload.serverFileExt neq "xlsx") {
									error = "Selected file is not an Excel spreadsheet";
									// ui = "error";
									fileDelete(uploadFile);
								}									
							break;
						};
					} else {
						error = "Upload failed";
					};
				} else {
					error = "Required value(s) missing from submission";
				};*/
			break;
			case "export":
				// default export format to csv, override in switch case for Excel (use "xls")
				exportFormat = "csv";
				switch(args.collection) {
					case "orders":
						//orderGateway = new assets.csac.com.gateway.OrderGateway();
						data = request.orderGateway.query();
						cols = data.ColumnList;
					break;
					case "users":
						//userGateway = new assets.csac.com.gateway.UserGateway();
						data = request.userGateway.query();
						cols = data.ColumnList;
						/*cols = "USER_ID,					
								APPROVED,
								ARCHIVED,
								DELETED,
								FIRST_NAME,
								LAST_NAME,
								FULL_NAME,
								TITLE,
								ROLE,
								REGION_IDS,
								PHONE,
								EXTENSION,
								EMAIL,
								WORKSHOP_COUNT,
								ORDER_COUNT,
								ORGANIZATION_ID,
								ORGANIZATION,
								ORGANIZATION_APPROVED,
								ORGANIZATION_ARCHIVED,
								ORGANIZATION_DELETED,
								COUNTY,
								REGION,
								REGION_ID,
								DATE_CREATED,
								QUERY_DATE";*/
					break;
					default:
						error = "Collection not found";
				};
			break;
			case "saveOrder":
				order = request.orderGateway.save(argumentCollection = args);
				args.origin = "CSAC";
				if (NOT IsInstanceOf(order, "assets.csac.com.bo.Order")) {
					error = order;
				}
			break;
			/*case "saveOrderStatus":
				order = request.orderGateway.save(argumentCollection = args);
				args.origin = "CSAC";
				if (NOT IsInstanceOf(order, "assets.csac.com.bo.Order")) {
					error = order;
				}
			break;*/
			case "deleteOrder":
				result = request.orderGateway.delete(argumentCollection = args);
				if (NOT IsBoolean(result)) {
					error = result;
				}
			break;
			case "saveProduct":
				product = request.productGateway.save(argumentCollection = args);
				if (NOT IsInstanceOf(product, "assets.csac.com.bo.Product")) {
					error = product;
				}
			break;
			case "saveProductCategory":
				productCategory = request.productCategoryGateway.save(argumentCollection = args);
				if (NOT IsInstanceOf(productCategory, "assets.csac.com.bo.ProductCategory")) {
					error = productCategory;
				}
			break;
			case "saveProductCategoriesOrder":
				for (i=1; i lte ListLen(args.productCategoryIDsOrder); i++) {
					pcArgs = {};
					pcArgs.Product_Category_ID = ListGetAt(args.productCategoryIDsOrder, i);
					pcArgs.Sort_Order = i * 10;
					request.productCategoryGateway.save(argumentCollection = pcArgs);
				}
			break;
			case "saveUser":
				user = request.userGateway.save(argumentCollection = args);
				if (NOT IsInstanceOf(user, "assets.csac.com.bo.User")) {
					error = user;
				}
			break;
			case "deleteUser":
				result = request.userGateway.delete(argumentCollection = args);
				if (NOT IsBoolean(result)) {
					error = result;
				}
			break;
			case "emailPassword":
				emailSent = request.base.emailPassword(Email = args.Email);
				if (emailSent) {
					ArrayAppend(request.alerts, "Your password has been sent to #args.Email#");
				} else {
					ArrayAppend(request.alerts, "There was a problem sending your password to #args.Email#.  Please try again.");
				}
			break;
			default:
				error = "Action not found";
		}
	}
</cfscript>

<cfif action eq "export" and IsDefined("exportFormat") and IsDefined("collection") and IsDefined("data") and IsQuery(data)>
	<cfif NOT DirectoryExists(request.tempDirectory)>
		<cfdirectory directory="#request.tempDirectory#" action="create" />
	</cfif>
	
	<!--- Get a list of export files in the application temp directory --->
	<cfdirectory action="list" directory="#request.tempDirectory#" name="tempFiles" />
	<cfloop query="tempFiles">
		<!--- Delete files more than a day old --->
		<cfif DateLastModified lt DateAdd("d", -1, Now())>
			<cffile action="delete" file="#Directory#\#Name#">
		</cfif>
	</cfloop>
	
	<cfset exportFilename = "#collection#_#DateFormat(now(), 'yyyy-mm-dd')#-#TimeFormat(now(), 'HH-mm-ss-L')#.#exportFormat#" />
	
	<cfswitch expression="#exportFormat#">
		<cfcase value="csv">
			<!--- Output as content stream which will trigger a download --->
			<cfheader name="Content-Disposition" value="attachment; filename=#exportFilename#">
			<cfcontent type="text/csv">
			<cfoutput>#request.base.queryToCSV(data, cols, true, ",")#</cfoutput>
			<cfabort>
		</cfcase>
		<cfcase value="xls">
			<!--- Generate Excel file in application temp directory --->
			<cfspreadsheet action="write" filename="#request.tempDirectory##exportFilename#" overwrite="true" query="data" sheetname="#collection#">
			<!--- Relocate to the generated file for download --->
			<cflocation url="#request.pathToTemp##exportFilename#" addtoken="no">
		</cfcase>
	</cfswitch>
</cfif>

<!--- <cfif action eq "import" and IsDefined("uploadFile") and FileExists(uploadFile)>
	<cfspreadsheet action="read" src="#uploadFile#" query="importData" headerrow="1" excludeheaderrow="true">
<cfelseif action eq "export" and IsDefined("exportFormat") and IsDefined("collection") and IsDefined("data") and IsQuery(data)>
	<cfif NOT DirectoryExists(request.tempDirectory)>
		<cfdirectory directory="#request.tempDirectory#" action="create" />
	</cfif>
	
	<!--- Get a list of export files in the application temp directory --->
	<cfdirectory action="list" directory="#request.tempDirectory#" name="tempFiles" />
	<cfloop query="tempFiles">
		<!--- Delete files more than a day old --->
		<cfif DateLastModified lt DateAdd("d", -1, Now())>
			<cffile action="delete" file="#Directory#\#Name#">
		</cfif>
	</cfloop>
	
	<cfset exportFilename = "#collection#_#DateFormat(now(), 'yyyy-mm-dd')#-#TimeFormat(now(), 'HH-mm-ss-L')#.#exportFormat#" />
	
	<cfswitch expression="#exportFormat#">
		<cfcase value="csv">
			<!--- Output as content stream which will trigger a download --->
			<cfheader name="Content-Disposition" value="attachment; filename=#exportFilename#">
			<cfcontent type="text/csv">
			<cfoutput>#request.base.queryToCSV(data, cols, true, ",")#</cfoutput>
			<cfabort>
		</cfcase>
		<cfcase value="xls">
			<!--- Generate Excel file in application temp directory --->
			<cfspreadsheet action="write" filename="#request.tempDirectory##exportFilename#" overwrite="true" query="data" sheetname="#collection#">
			<!--- Relocate to the generated file for download --->
			<cflocation url="#request.pathToTemp##exportFilename#" addtoken="no">
		</cfcase>
	</cfswitch>
</cfif> --->